package com.moarea.app.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

public abstract class FileExport {
	
	private String fileName="";
	private List<Map<String,Object>> dataMap;			
	private AnyFormatDocProp prop;
	public InputStream getInputStream()throws  Exception{
		CreateXlsFormatDocument xslTxt = new CreateXlsFormatDocument(prop,dataMap);
		if(AnyFormatDocumentConstant.SIMPLE_MODE.equals(prop.getMode())){
			return new ByteArrayInputStream(xslTxt.createContentSimple().getBytes());
		}
		xslTxt.createContent();
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		xslTxt.getWbout().write(bout);
		byte[] content = bout.toByteArray();
		    
		try{
			
		    return new ByteArrayInputStream(content);
		}
		catch(Exception e){
		  e.printStackTrace();
		  throw new RuntimeException("生成文本错误,系统发生严重错误!");
		}
		finally{
		  if(bout != null)
			  bout.close();  
	  }
	}
	public List<Map<String, Object>> getDataMap() {
		return dataMap;
	}
	public void setDataMap(List<Map<String, Object>> dataMap) {
		this.dataMap = dataMap;
	}
	public AnyFormatDocProp getProp() {
		return prop;
	}
	public void setProp(AnyFormatDocProp prop) {
		this.prop = prop;
	}
	public String getFileName(HttpServletRequest request) throws UnsupportedEncodingException {
		if (!StringUtils.isNotEmpty(fileName))
		{
		fileName="文档.xls"; 
		}
		 String agent = request.getHeader("USER-AGENT");  
         if (null != agent && -1 != agent.indexOf("MSIE") || null != agent  
                 && -1 != agent.indexOf("Trident")) {// ie  
        	 return java.net.URLEncoder.encode(fileName, "UTF8");
         } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等  
             return new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
         }  
         return new String(fileName.getBytes("UTF-8"), "iso-8859-1");  
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public abstract void loadData();
	
	protected String getString(Object obj){
		if(obj == null)
			return "";
		else
			return obj.toString();
	}

}
